import $ from 'jquery'
import {
  Message,
  MessageBox
} from 'element-ui'

const showMessage = function (content, type) {
  Message({
    message: content,
    type: type,
    showClose: true,
    duration: 3000
  })
}

// 图片下载
function getBlob(url) {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();

    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };

    xhr.send();
  });
}

function saveAs(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    const link = document.createElement('a');

    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.dispatchEvent(new MouseEvent('click', {
      bubbles: true,
      cancelable: true,
      view: window
    }));

    window.URL.revokeObjectURL(link.href);
  }
}

export default {
  getDate(date) {
    if (!date) {
      return new Date()
    }

    var theDate = ''
    if (typeof date == 'number') {
      theDate = new Date(date)
    } else if (date.length === undefined) {
      theDate = date
    } else {
      if (date.length > 10) {
        var dateArr = date.split(/[T\s]/)

        var beforeTime = dateArr[0].split('-')
        var afterTime = dateArr[1].split(':')

        afterTime[2] = afterTime[2] ? afterTime[2] : '00'
      } else {
        var beforeTime = date.split('-')
      }

      if (afterTime) {
        theDate = new Date(beforeTime[0], beforeTime[1] - 1, beforeTime[2], afterTime[0], afterTime[1], afterTime[2])
      } else {
        theDate = new Date(beforeTime[0], beforeTime[1] - 1, beforeTime[2])
      }
    }
    if (!theDate) {
      theDate = new Date()
    }

    return theDate
  },
  /**
   * 格式化日期函数
   * @param date {Date|Date String} [需要格式化的日期]
   * @param frm {String} [格式(如：yyyy-MM-dd hh:mm:ss)]
   * @return 格式化后的日期
   */
  formatDate(date, fmt) {
    fmt = fmt ? fmt : 'yyyy-MM-dd hh:mm:ss'
    if (!date || !fmt) {
      return false
    }

    let theDate = new Date(date)
    var o = {
      'M+': theDate.getMonth() + 1, // 月份
      'd+': theDate.getDate(), // 日
      'h+': theDate.getHours(), // 小时
      'm+': theDate.getMinutes(), // 分
      's+': theDate.getSeconds(), // 秒
      'q+': Math.floor((theDate.getMonth() + 3) / 3), // 季度
      'S': theDate.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (theDate.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
  },
  formDataDate(str) {
    var dateStr = new Date(str)
    var year = dateStr.getFullYear()
    var monthStr = dateStr.getMonth() + 1
    var dayStr = dateStr.getDate()
    var month = monthStr < 10 ? '0' + monthStr : monthStr
    var day = dayStr < 10 ? '0' + dayStr : dayStr
    return year + '-' + month + '-' + day
  },
  formDataTime(str) {
    var dateStr = new Date(str)
    var hours = dateStr.getHours()
    var minutes = dateStr.getMinutes()
    var seconds = dateStr.getSeconds()
    hours = hours < 10 ? '0' + hours : hours
    minutes = minutes < 10 ? '0' + minutes : minutes
    seconds = seconds < 10 ? '0' + seconds : seconds
    return hours + ':' + minutes + ':' + seconds
  },
  /**
   * 获取上一个月
   *
   * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
   */
  getPreMonth(date) {
    var arr = date.split('-')
    var year = arr[0] //获取当前日期的年份
    var month = arr[1] //获取当前日期的月份
    var days = new Date(year, month, 0)
    days = days.getDate() //获取当前日期中月的天数
    var year2 = year
    var month2 = parseInt(month) - 1
    if (month2 == 0) {
      year2 = parseInt(year2) - 1
      month2 = 12
    }
    var days2 = new Date(year2, month2, 0)
    days2 = days2.getDate()
    if (month2 < 10) {
      month2 = '0' + month2
    }
    var t2 = year2 + '-' + month2
    return t2
  },
  /**
   * 获取下一个月
   *
   * @date 格式为yyyy-mm的日期，如：2014-01
   */
  getNextMonth(date) {
    var arr = date.split('-')
    var year = arr[0] //获取当前日期的年份
    var month = arr[1] //获取当前日期的月份
    var days = new Date(year, month, 0)
    days = days.getDate() //获取当前日期中的月的天数
    var year2 = year
    var month2 = parseInt(month) + 1
    if (month2 == 13) {
      year2 = parseInt(year2) + 1
      month2 = 1
    }
    var days2 = new Date(year2, month2, 0)
    days2 = days2.getDate()
    if (month2 < 10) {
      month2 = '0' + month2
    }

    var t2 = year2 + '-' + month2
    return t2
  },
  rangeFn: function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  dateDiff(startTime, endTime) {
    var start = startTime ? new Date(startTime) : new Date();
    var end = endTime ? new Date(endTime) : new Date();
    return Math.round((end - start) / 1000 / 60 / 60 / 24)
  },
  downloadFile(url, filename) {
    filename = filename || url.substr(url.lastIndexOf('/') + 1)
    const pattern = /[`~!@#$^&*()=|{}':;',\\\[\]\<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g;
    filename = filename.replace(pattern, "");
    getBlob(url).then(blob => {
      saveAs(blob, filename)
    })
  },
  isArray(o) {

    return Object.prototype.toString.call(o) == '[object Array]';

  },

};

/**
 * 数据 按照 拼音首字母 排序 并分组
 * 
 * @param {Json} data ; 需要 排序的 数据
 * @param {String} field ；必须；排序所依据的 字段 名
 * 
 * @return {Json} ; 例如：{A:[{},{}],B:[{},{}],C:[{}],#:[]}
 **/
function data_letter_sort(data, field) {
  var letter_reg = /^[A-Z]$/;
  var list = new Array();
  for (var i = 0; i < data.length; i++) {
    // 首字母 转 大写英文
    var letter = (data[i][field]).substr(0, 1).toUpperCase();

    // 是否 大写 英文 字母
    if (!letter_reg.test(letter)) {
      letter = '#';
    }
    // 创建 字母 分组
    if (!(letter in list)) {
      list[letter] = new Array();
    }
    // 字母 分组 添加 数据
    list[letter].push(data[i]);
  }

  // 转换 格式 进行 排序；
  var resault = new Array();
  for (var key in list) {
    resault.push({
      letter: key,
      list: list[key]
    });
  }
  resault.sort(function (x, y) {
    return x.letter.charCodeAt(0) - y.letter.charCodeAt(0);
  });
  // # 号分组 放最后
  var last_arr = resault[0];
  resault.splice(0, 1);
  resault.push(last_arr);

  // 转换 数据 格式
  var json_sort = {}
  for (var i = 0; i < resault.length; i++) {
    json_sort[resault[i].letter] = resault[i].list;
  }
  return json_sort;
}

function formMonthDate(str) {
  var dateStr = new Date(str)
  var year = dateStr.getFullYear()
  var monthStr = dateStr.getMonth() + 1
  var dayStr = dateStr.getDate()
  var month = monthStr < 10 ? '0' + monthStr : monthStr
  return year + '-' + month
}

//防止重复点击，1秒半间隔后可重新点击
function banManyClick(em) {
  if (em.isPost) {
    em.$toast('请勿重复提交');
    return false;
  }
  em.isPost = true;
  setTimeout(() => {
    em.isPost = false;
  }, 1500);
  return true;
}

//通用校验保存
function formValid(that, formName, saveFn) {
  that.$refs[formName].validate(valid => {
    if (valid) {
      if (that.ISPOST) {
        that.$message({
          message: '操作太频繁！',
          type: 'warning',
        });
        // return true;
      }
      if (!that.ISPOST) {
        saveFn()
      }
      that.ISPOST = true;
      setTimeout(() => {
        that.ISPOST = false;
      }, 3000);
    } else {
      that.$message({
        message: '请输入必填项!',
        type: 'warning'
      });
    }
  });
}

//-连接的字符串变为驼峰命名
function transformStr(str) {
  var re = /-(\w)/g;
  return str.replace(re, function ($0, $1) {
    return $1.toUpperCase();
  });
}

//首字母致为小写
function titleCase(str) {
  var newarr, newarr1 = [];
  newarr = str.split(" ");
  for (var i = 0; i < newarr.length; i++) {
    newarr1.push(newarr[i][0].toLowerCase() + newarr[i].substring(1));
  }
  return newarr1.join(' ');
}

// 函数防抖
const debounce = (fn, delay) => {
  let times = delay || 200
  let timer
  return function () {
    let _this = this
    let args = arguments
    timer && clearTimeout(timer)
    timer = setTimeout(function () {
      timer = null
      fn.apply(_this, args)
    }, times)
  }
}


const conventTreeData = function (children) {
  let parent = arguments[1] || undefined
  let props = arguments[2] ? arguments[2] : {
    children: 'children',
    label: 'label',
    value: 'value'
  }
  let res = []
  if (children && children.length > 0) {
    children.forEach(c => {
      let cc = c[props.children]
      let child = {
        label: c[props.label],
        value: c[props.value],
        parent: parent
      }
      if (cc && cc.length > 0) {
        child.children = conventTreeData(cc, c, props)
      }
      res.push(child)
    })
  }
  return res
}

//除法
const accDiv = function (arg1, arg2) {
  if (arg1 == null || arg2 == 0) {
    return 0;
  }
  if (arg2 == null || arg2 == 0) {
    return 0;
  }
  var n1, n2;
  var r1, r2; // 小数位数
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  n1 = Number(arg1.toString().replace(".", ""));
  n2 = Number(arg2.toString().replace(".", ""));
  return (n1 / n2) * Math.pow(10, r2 - r1);
}
//乘法 
const accMul = function (arg1, arg2) {
  if (arg1 == null || arg2 == null) {
    return null;
  }
  var n1, n2;
  var r1, r2; // 小数位数
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  n1 = Number(arg1.toString().replace(".", ""));
  n2 = Number(arg2.toString().replace(".", ""));
  return n1 * n2 / Math.pow(10, r1 + r2);
}
//加法 
const accAdd = function (arg1, arg2) {
  var r1, r2, m;
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  return (arg1 * m + arg2 * m) / m
}
//减法 
const accSubtr = function (arg1, arg2) {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2));
  n = (r1 >= r2) ? r1 : r2;
  return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
}

const requestTips = function (item, cb) {
  console.log(item)
  if (item.success) {
    showMessage(item.message, "success")
    cb && cb()
  } else {
    showMessage(item.message, "error")
  }
}

//询问弹框
const askDialog = function (msg, cb) {
  MessageBox.confirm(msg, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    cancelButtonClass: 'el-button--mini',
    confirmButtonClass: 'el-button--mini',
    type: 'warning'
  }).then(
    cb
  ).catch(() => {})
}

//判断平年润年
const isLeapYear = function (year) {
  if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
    return true
  } else {
    return false
  }
}

//js 计算两个日期之间 相差几年几月几日
const monthDayDiff = function (startTime, endTime) {
  let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2];
  let start = new Date(startTime);
  let end = new Date(endTime);
  let year = end.getFullYear() - start.getFullYear();
  let month = end.getMonth() - start.getMonth();
  let day = end.getDate() + 1 - start.getDate();
  if (month < 0) {
    year--;
    month = end.getMonth() + (12 - start.getMonth());
  }
  if (day < 0) {
    month--;
    let isLeapYearFlag = isLeapYear(start.getFullYear());
    let index = flag.findIndex((temp) => {
      return temp === start.getMonth() + 1
    });
    let monthLength;
    if (index <= 6) {
      monthLength = 31;
    } else if (index > 6 && index <= 10) {
      monthLength = 30;
    } else {
      monthLength = isLeapYearFlag ? 29 : 28;
    }
    day = end.getDate() + (monthLength - start.getDate());
  } else {
    let isLeapYearFlag = isLeapYear(end.getFullYear());
    let index = flag.findIndex((temp) => {
      return temp === end.getMonth() + 1
    });
    let monthLength;
    if (index <= 6) {
      monthLength = 31;
    } else if (index > 6 && index <= 10) {
      monthLength = 30;
    } else {
      monthLength = isLeapYearFlag ? 29 : 28;
    }
    if (day == monthLength) {
      day = 0
      month = month + 1
    }
  }
  return {
    year: year,
    month: month,
    day: day,
  }
}

const fmoneyThousand = (s, n) => {
  if (s < 0) {
    var oldVal = s
    s = Math.abs(s)
  }
  n = n > 0 && n <= 20 ? n : 2;
  s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + '';
  var l = s.split('.')[0].split('').reverse(),
    r = s.split('.')[1],
    t = '';
  for (let i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? ',' : '');
  }
  let val = t.split('').reverse().join('') + '.' + r;
  return oldVal < 0 ? "-" + val : val
}

//询问弹框
const getDay = function (timestamp) {
  var total = timestamp / 1000;
  var day = parseInt(total / (24 * 60 * 60)); //计算整数天数
  return day
}

const guid = function () {
  return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

const formDataDate = function (str) {
  var dateStr = new Date(str)
  var year = dateStr.getFullYear()
  var monthStr = dateStr.getMonth() + 1
  var dayStr = dateStr.getDate()
  var month = monthStr < 10 ? '0' + monthStr : monthStr
  var day = dayStr < 10 ? '0' + dayStr : dayStr
  return year + '-' + month + '-' + day
}

const getLastDay = function (data) {
  var y = new Date(data).getFullYear(); //获取年份
  var m = new Date(data).getMonth() + 1; //获取月份
  var d = new Date(y, m, 0).getDate(); //获取当月最后一日
  m = m < 10 ? '0' + m : m; //月份补 0
  d = d < 10 ? '0' + d : d; //日数补 0

  return d;
}

const getLocation = function () {
  let locationVal = null;
  if (location.hostname == "pms.block-os.com" || location.hostname == "opm.jh-sg.com" || location.hostname == "sit-pms-rent.block-os.com" || location.port == "10621") {
    locationVal = "operationManagement"; //阳光数字商管
  } else if (location.hostname == "commercial-rent.block-os.com" || location.hostname == "pam.jh-sg.com" || location.hostname == "sit-commercial-rent.block-os.com" || location.port == "10619") {
    locationVal = "assetManagement"; //阳光数字资管
  } else if (location.hostname == "bom.block-os.com" || location.hostname == "bom.jh-sg.com" || location.hostname == "sit-bom.block-os.com" || location.port == "106192") {
    locationVal = "businessBuildingOperate"; //商写运营
  }
  return locationVal;
}

const getSystemName = function () {
  let systemName = '';
  let systemType = getLocation();
  if (systemType == 'operationManagement') {
    systemName = '阳光数字商管';
  } else if (systemType == 'assetManagement') {
    systemName = '阳光数字资管';
  } else if (systemType == 'businessBuildingOperate') {
    systemName = '商写运营';
  }
  return systemName;
}

//type 传值business将得到资管的相应域名 默认得到运管的相应域名
const getOperationOrigin = function (type) {
  let operationList = ["pms.block-os.com", "opm.jh-sg.com", "sit-pms-rent.block-os.com"] //运管的两个域名
  let businessList = ["commercial-rent.block-os.com", "pam.jh-sg.com", "sit-commercial-rent.block-os.com"] //资管的两个域名
  let index = ""
  if (type == 'business') {
    index = operationList.indexOf(location.hostname)
  } else {
    index = businessList.indexOf(location.hostname)
  }
  if (index === '' || index < 0) return "sit-commercial-rent.block-os.com"
  return type == 'business' ? businessList[index] : operationList[index]
}

//如果是小数 保留两位
const toFixedTwo = function (num) {
  num = Number(num);
  let isInt = Number.isInteger(num);
  return isInt ? num : Number(num.toFixed(2));
}

// 去项目详情
const goOperationIndex = function (key) {
  let host = getOperationOrigin();
  let urlPath = '/pcIndex?';
  window.open('https://' + host + urlPath + 'isPointLogin=true&token=' + localStorage.getItem('token') + '&selectProjectKey=' + key);
}

//下载
const uploadLoad = function (url) {
  let a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

//字段回显
const setFiledVal = function (list, row) {
  list.forEach(item => {
    for (let i in row) {
      if (i == item.bindFieldName) {
        // if (typeof row[i] === 'number' && !isNaN(row[i])) {
        //   row[i] = String(row[i]);
        // }
        item.bindFieldVal = row[i];
      }
    }
  });
}

//生成随机数
// 生成3-32位随机串：randomWord(true, 3, 32)
// 生成43位随机串：randomWord(false, 43)
const randomWord = function (randomFlag, min, max) {
    var str = "",
      pos = "",
      range = min,
      // arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

    // 随机产生
    if (randomFlag) {
      range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
      pos = Math.round(Math.random() * (arr.length - 1));
      str += arr[pos];
    }
    return str;
  }

  const formatDate = function(date, fmt) {
    fmt = fmt ? fmt : 'yyyy-MM-dd hh:mm:ss'
    if (!date || !fmt) {
      return false
    }

    let theDate = new Date(date)
    var o = {
      'M+': theDate.getMonth() + 1, // 月份
      'd+': theDate.getDate(), // 日
      'h+': theDate.getHours(), // 小时
      'm+': theDate.getMinutes(), // 分
      's+': theDate.getSeconds(), // 秒
      'q+': Math.floor((theDate.getMonth() + 3) / 3), // 季度
      'S': theDate.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (theDate.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
  }

  const cutFileName = function (fileName) {
    let num = fileName.lastIndexOf('_');
    let len = fileName.length;
    let cutFileName = fileName.substring(num + 1, len);
    return cutFileName;
  }

  export {
    data_letter_sort,
    banManyClick,
    formValid,
    transformStr,
    titleCase,
    debounce,
    conventTreeData,
    accDiv,
    accMul,
    accAdd,
    accSubtr,
    requestTips,
    askDialog,
    showMessage,
    getDay,
    formMonthDate,
    guid,
    fmoneyThousand,
    monthDayDiff,
    formDataDate,
    getLastDay,
    getLocation,
    getSystemName,
    getOperationOrigin,
    toFixedTwo,
    goOperationIndex,
    uploadLoad,
    isLeapYear,
    setFiledVal,
    randomWord,
    formatDate,
    cutFileName
  };
